<template>
	<view class="card-box">
		<view class="select_pay_box ">
			<view class="title b-tottom p20">
				<text class="tip">请选择支付方式</text>
			</view>

			<view v-for="(item,index) in paySetting.payList" :key="index"  @click="pay_code=item.pay_code">
				<view class="space-between p20 pt30 pb30 b-tottom">
					<view class="smll">
						<view class="img mr20">
							<u-image :src="payImgList[item.pay_code]" mode="widthFix"></u-image>
						</view>
						<view class="fs28">{{item.pay_name}}</view>
						<view class="money  ff">
							<view v-if="item.money >= 0">
							（剩余<text class="fs24 base-color">￥</text>
								<text class="fs40 base-color">{{item.money}}</text> ）
							</view>
						</view>
					</view>

					<view v-if="pay_code == item.pay_code">
						<view class="item_icon bg-base" >
							<u-icon class="u-icon" name="checkbox-mark" color="#FFFFFF" size="26"></u-icon>
						</view>
					</view>
					<view v-else class="check-defaul"></view>
				
				</view>
			</view>
		</view>
		<view v-if="pay_code=='offline'" class="mt20">
			<view class="fs30 color-baseb" v-if="paySetting.offline.is_sys == 0">
				线下转帐给上级会员，以下为上级会员的收款信息
			</view>
			<view class="offline_box " v-if="paySetting.offline.weixin_usd == 1">
				<view class="title">
					<u-image class="icon" src="/static/public/images/pay/weixin.png" shape="circle"></u-image>微信转帐
				</view>
				<view class="info">
					<view>帐户姓名：{{paySetting.offline.weixin_name}}</view>
					<view>微信号：{{paySetting.offline.weixin_account}}</view>
					<u-image mode="widthFix" :src="baseUrl+paySetting.offline.weixin_qrcode"></u-image>
				</view>
			</view>
			<view class="mt20 offline_box" v-if="paySetting.offline.alipay_usd == 1">
				<view class="title alipay">
					<u-image class="icon" src="/static/public/images/pay/alipay.png" shape="circle"></u-image>支付宝转帐
				</view>
				<view class="info">
					<view>帐户姓名：{{paySetting.offline.alipay_name}}</view>
					<view>支付宝帐户：{{paySetting.offline.alipay_account}}</view>
					<u-image mode="widthFix" :src="baseUrl+paySetting.offline.alipay_qrcode"></u-image>
				</view>
			</view>
			<view v-if="paySetting.offline.bank_usd == 1" class="mt20  offline_box">
				<view class="title bank">
					<u-image class="icon" src="/static/public/images/pay/bank.png" shape="circle"></u-image>银行转帐
				</view>
				<view class="fs32  p20">
					<view>开户银行：{{paySetting.offline.bank_name}}</view>
					<view>开户支行：{{paySetting.offline.bank_subbranch}}</view>
					<view>持卡人姓名：{{paySetting.offline.bank_user_name}}</view>
					<view>银行卡号：{{paySetting.offline.bank_card_number}}</view>
				</view>
			</view>
			<view v-if="paySetting.offline.is_usd == 1" class=" bg-white post—box p20">
				<view class="title">请提交付款凭证：</view>
				<view class="mt20">
					<u-upload ref="upload" @on-change="uploaded" @on-remove="removeImg" :action="upAction" max-count="6"></u-upload>
				</view>
				<button class="primarybtn mt20 pay-btn fs30" type="warning"  :loading="isLoading" @click="postOffLine">立即提交</button>
			</view>
			<view v-else class="p40 mt20 text-center base-color">上级未设置线下收款信息</view>
		</view>
		<view v-if="pay_code == 'alipayMobile'">
		<view class="u-demo-block">
			
					<text class="u-block__title">选择支付方式</text>
					<view class="u-demo-block__content">
						<view class="u-page__radio-item">
							<u-radio-group
								v-model="selectedPaymentMethod"
								placement="row"
								@change="handlePaymentMethodChange"
							>
								<u-radio :customStyle="{marginRight: '16px'}"
									v-for="(item, index) in paymentMethods"
									:key="index"
									:label="item.name"
									:value="item.val"
									:name="item.val"
							
								>
								   {{item.name}}
								</u-radio>
							</u-radio-group>
						</view>
					</view>
				</view>
		</view>
		  <!-- 假设的二维码显示区域 -->  
		      <view v-if="qrcodeVisible" class="qrcode-display">  
		        <!-- 在这里展示二维码 -->  
		        <text> <image  :src="paySetting.qrcode" mode="aspectFit"></image> </text>  
		      </view> 
		
		<button v-if="pay_code!='' && pay_code!='offline' && payshow" class="mt20 primarybtn pay-btn fs30" type="warning"  :loading="isLoading"
		 @click="pay">立即支付</button>
	</view>
</template>


<script>
	
	export default {
		name: "payBox",
		props: {
			paySetting: {
				type: Object,
				default: function() {
					return {};
				}
			},
			payType: {
				type: String,
				default: ''
			},
			from: {
				type: String,
				default: ''
			},
			order_id: {
				type: Number,
				default: 0
			},
			model: {
				type: Object,
				Object,
				default: function() {
					return {};
				}
			},
		},
		data() {
			return {
				baseUrl: this.config.baseUrl,
				isLoading: false,
				searchText: '',
				showSelectBox: true,
				pay_code: '',
			//横向排列形式数据
			   selectedPaymentMethod: 'H5', // 用户选择的支付方式  
			    qrcodeVisible: false, // 控制二维码显示与否  
			    currentPaymentMethod: '', // 当前要显示的支付方式的名称  
				payshow:true, 
				//radiovalue6: 'H5',
				//paymentMethods:'H5',
				pay_type:'', 
	
				paymentMethods: [{
						name:'H5',
						val:'H5', 
						disabled: false
					},
					{
						name:'当面付',
						val:'face',
						disabled: false
					},
					// {
					// 	name:'JsApi',
					// 	val:'jsApi',
					// 	disabled: false
					// },
				],
				upAction: this.config.upImageUrl,
				fileList: [],
				payImgList: {
					balance: '/static/public/images/pay/balance.png',
					weixin: '/static/public/images/pay/weixin.png',
					appWeixinPay: '/static/public/images/pay/weixin.png',
					miniAppPay: '/static/public/images/pay/weixin.png',
					alipayMobile: '/static/public/images/pay/alipay.png',
					alipayApp: '/static/public/images/pay/alipay.png',
					offline: '/static/public/images/pay/bank.png',
					goodsMoney: '/static/public/images/pay/goodsmoney.png',
					uplevelGoodsMoney: '/static/public/images/pay/goodsmoney.png',
				},
				orderInfo: {}
			}
		},
		methods: {
			
	
	     //doc new 	qrcode show pay authour ice
		      
		async checkOrderStatus(orderId) {  
		  let params = { order_id: orderId };  
		  let url = 'publics/api.pay/queryOrder';  
		  
		  try {  
		    let res = await this.$u.post(url, params);  
		    if (res.code === 1) {  
		      return 'SUCCESS'; // 直接返回成功字符串  
		    } else {  
		      throw new Error('FAIL'); // 抛出错误，而不是返回拒绝的 Promise  
		    }  
		  } catch (error) {  
		    throw new Error('Network Error or Other Issues'); // 抛出包含错误信息的错误  
		  }  
		},
		 
			 handlePaymentMethodChange(newValue) {  
			      // 当选中的支付方式变化时执行  
				   // console.log(newValue);  
				this.pay_type = newValue;
			      if (newValue === 'face') {  
			        this.showalipayQrcode(newValue);  
			      }else{
					   this.payshow=true;
					    this.qrcodeVisible = false; // 显示二维码
				  }  
			      // 这里可以根据 newValue 的值来执行不同的操作  
			    },  
				 
			   showalipayQrcode(paymentMethod) {  
			     let intervalId = null; // 确保在函数内部定义  
			     this.payshow = false;  
			     this.qrcodeVisible = true;  
			     this.currentPaymentMethod = this.paymentMethods.find(pm => pm.val === paymentMethod).name;  
			     
			     // 设置定时器  
			     intervalId = setInterval(async () => {  
			       try {  
			         let status = await this.checkOrderStatus(this.order_id);  
			         if (status === 'SUCCESS') {  
			           uni.navigateTo({  
			             url: '/pages/shop/order/list'  
			           });  
			           clearInterval(intervalId); // 现在 intervalId 是有效的  
			         }  
			       } catch (error) {  
			         console.error('Error checking order status:', error);  
			         // 可以选择在这里处理错误，比如显示一个错误消息  
					  //  clearInterval(intervalId);
			         // 如果错误持续发生，您可能还想考虑停止定时器  
			       }  
			     }, 5000);  
			   },
				// 假设的检查订单状态的函数  
			
			postOffLine() {
				if (this.isLoading == true) {
					return false;
				}
				if (this.fileList.length < 1) {
					this.$u.toast('请上传付款凭证.');
					return false;
				}
				this.isLoading = true;
				let order_id = this.order_id;
				let payType = this.payType;
				let from = this.from;
				let url = '';
				let data = {};

				if (payType == 'order' || payType == 'fgorder') {
					if (from == 'shop') {
						url = 'shop/api.order/postOffLinePay';
					} else if (from == 'channel') {
						url = 'channel/api.order/postOffLinePay';
					} else {
						return this.$u.toast('请求错误.');
					}
					data.order_id = order_id;
					data.fileList = this.fileList.join(',');
				} else if (payType == 'recharge') { //充值处理
					data = this.model;
					if (data.money == '' || data.money <= 0) {
						this.isLoading = false;
						return this.$u.toast('请输入充值金额.');
					}
					data.fileList = this.fileList.join(',');
					data.payCode = 'offline';
					if (from == 'member') {
						url = 'member/api.wallet/postRecharge';
					} else if (from == 'channel') {
						url = 'channel/api.wallet/postRecharge';
					} else {
						return this.$u.toast('请求错误.');
					}
				}
				this.$u.post(url, data).then(res => {
					this.isLoading = false;
					uni.redirectTo({
						url: `/pages/public/pay/paySuccess?from=${from}&type=${payType}&order_id=${order_id}&pay_code=offline`
					});
				}).catch(res => {
					this.isLoading = false;
				})

			},
			async pay() {
				if (this.isLoading == true) {
					return false;
				}
				this.isLoading = true;
				let order_id = this.order_id;
				let from = this.from;
				let url = '';
				//充值处理，先创建充值订单，返回订单ID
				if (this.payType == 'recharge') {
					let data = this.model;
					if (data.money == '' || data.money <= 0) {
						this.isLoading = false;
						return this.$u.toast('请输入充值金额.');
					}
					data.payCode = this.pay_code;
					if (from == 'member') {
						url = 'member/api.wallet/postRecharge';
					} else if (from == 'channel') {
						url = 'channel/api.wallet/postRecharge';
					} else {
						return this.$u.toast('请求错误.');
					}
					let res = await this.$u.post(url, data).catch(res => {})
					this.isLoading = false;
					order_id = res.data.order_id;
					if (order_id < 1) return false;
				}
				// this.app.goPage('/pages/public/pay/payIng?from=' + this.from + '&pay_code=' + this.pay_code + '&payType=' + this.payType +
				// 	'&order_id=' + order_id + '&route=' + route,-1)
				this.isLoading = false;
				this.goPay();
			},
			uploaded(res, index, lists) {
				var res = JSON.parse(res.data);
				this.fileList.push(res.file);
			},
			removeImg(index, lists) {
				let file = this.fileList[index];
				this.fileList.splice(index, 1);
				this.$u.post(this.config.removeImageUrl, {
					file: file
				}).then(res => {})
			},
			async goPay(){
				let route = '/pages/public/pay/paySuccess';
				switch (this.pay_code) {
					case 'alipayMobile':
					case 'alipayApp':
					//this.payType = this.pay_type
					 // console.log(this.pay_type)
						//await this.$mPayment.aliPay(this,this.pay_code,this.from,this.this.selectedPaymentMethod,this.order_id,route);
						await this.$mPayment.aliPay(this,this.pay_code,this.from,this.payType,this.order_id,route);
						break;
					case 'weixin':
					case 'appWeixinPay':
						await this.$mPayment.weixinPay(this,this.pay_code,this.from,this.payType,this.order_id,route);
						break;
					case 'balance':
						await this.$mPayment.balancePay(this,this.pay_code,this.from,this.payType,this.order_id,route);
						break;
					case 'bean':
						await this.$mPayment.beanPay(this,this.pay_code,this.from,this.payType,this.order_id,route);
						break;
					case 'goodsMoney':
						await this.$mPayment.goodsMoneyPay(this,this.pay_code,this.from,this.payType,this.order_id,route);
					break;
					case 'uplevelGoodsMoney':
						await this.$mPayment.uplevelGoodsMoneyPay(this,this.pay_code,this.from,this.payType,this.order_id,route);
					break;
					default:
						this.app.showModal('暂不支持.',-1);
						break;
				}
			}
		}
	}
</script>

<style lang="scss">
	.card-box {
		margin: 20rpx;
		border-radius: 20rpx;
		background-color: #FFFFFF;
	}
	
	.u-demo-block{
	 margin: 20rpx;	
	}


.qrcode-display image {  
 margin-left: 60%;	
  width: 300rpx; /* 或者你需要的具体宽度 */  
  height: 300rpx; /* 保持图片宽高比 */  
}  
  
.qrcode-display {  
  width: 300rpx; /* 举例，rpx是微信小程序的响应式像素单位 */  
  height: 300rpx; /* 举例 */  
  display: flex; /* 微信小程序中不支持flex布局，这里只是示意 */  
  justify-content: center; /* 微信小程序中可能需要其他方式来实现居中 */  
  align-items: center;  
}

	.select_pay_box {
		.title {
			align-items: center;
			font-size: 36rpx;
			font-weight: 600;
			border-bottom: 1rpx solid $border-color-light;

			.tip {
				font-weight: normal;
				display: block;
				font-size: 26rpx;
				color: $font-color-light;
			}
		}


		.box {
			position: relative;
			height: 260rpx;
			width: calc(100% - 20rpx);
			overflow: hidden;
			text-align: center;
		}

		.img {
			width: 48rpx;
			height: 48rpx;

		}

		.item_icon {
			display: inline-block;
			width: 40rpx;
			height: 40rpx;
			border-radius: 50%;
			position: relative;
			margin: 0;
		}

		.u-icon {
			position: absolute;
			top: 6rpx;
			right: 0px;
			left: 0;
			z-index: 9;
			text-align: center;
			margin: 0 auto;
			display: flex;
			justify-content: center;
			align-items: center;
		}
	}

	.check-defaul {
		width: 40rpx;
		height: 40rpx;
		border: solid 1rpx #dddddd;
		border-radius: 50%;
	}

	.offline_box {
		line-height: 60rpx;

		.title {
			position: relative;
			padding-left: 100rpx;
			padding-top: 20rpx;
			padding-bottom: 20rpx;
			border-bottom: 1rpx solid #ccc;
			font-size: 40rpx;
			color: #FFFFFF;
			background-color: $uni-color-success;

			.icon {
				position: absolute;
				left: 20rpx;
				width: 60rpx !important;
				height: 60rpx !important;
			}

		}

		.alipay {
			background-color: $uni-color-primary;
		}

		.bank {
			background-color: $uni-color-error;
		}

		.info {
			padding: 20rpx;
			line-height: 60rpx;
			font-size: 30rpx;
		}
	}
	.u-page {
			&__style {
				font-size: 16px;
				color: rgb(96, 98, 102);
				margin-bottom: 20rpx;
				font-weight: bold;
			}
	
			&__title {
				font-size: 16px;
				color: rgb(96, 98, 102);
				margin-bottom: 20rpx;
			}
		}
	.pay-btn {
		margin-top: 120px;
	}
</style>
